/*
 * @Date: 2024-02-20 13:37:41
 * @LastEditors: lyx
 * @LastEditTime: 2024-02-20 13:37:48
 * @FilePath: \taro-template3\src\utils\chunk.ts
 * @Description: sse 接口返回处理
 */
export const arrayBufferToString = (arr) => {
  if (typeof arr === "string") {
    return arr;
  }
  let dataview = new DataView(arr);
  let ints = new Uint8Array(arr.byteLength);
  for (let i = 0; i < ints.length; i++) {
    ints[i] = dataview.getUint8(i);
  }
  let str = "",
    _arr = ints;
  for (let i = 0; i < _arr.length; i++) {
    if (_arr[i]) {
      let one = _arr[i].toString(2),
        v = one.match(/^1+?(?=0)/);
      if (v && one.length == 8) {
        let bytesLength = v[0].length;
        let store = _arr[i].toString(2).slice(7 - bytesLength);
        for (let st = 1; st < bytesLength; st++) {
          if (_arr[st + i]) {
            store += _arr[st + i].toString(2).slice(2);
          }
        }
        str += String.fromCharCode(parseInt(store, 2));
        i += bytesLength - 1;
      } else {
        str += String.fromCharCode(_arr[i]);
      }
    }
  }
  return str;
};

// 合并arrayBuffer
export const mergeArrayBuffers = (buffer1, buffer2) => {
  if (!buffer1) {
    return buffer2;
  } else if (!buffer2) {
    return buffer1;
  }
  let tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
  tmp.set(new Uint8Array(buffer1), 0);
  tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
  return tmp.buffer;
};
